/*
    定义绘画数据数据结构,绘画数据包含一组笔画，笔画包含 线宽、颜色和一组路径坐标(记录坐标时间)
    let drawData=[
        {
            width:12,
            color:'#000',
            posArr:[{x:0,y:0，delay:200}]
        }
    ]
*/

function drawByStrokeData(ctx, { lineWidth, color, posArr }, scale) {
  
  ctx.lineWidth = lineWidth
  ctx.strokeStyle = color
  ctx.beginPath()
  if (posArr && posArr.length > 0) {
    ctx.moveTo(posArr[0].x * scale, posArr[0].y * scale)
  }

  posArr.forEach(point => {
    ctx.lineTo(point.x * scale, point.y * scale)
  })
  ctx.stroke()
}

function reStroke(ctx, strokeData, scale) {
  return new Promise(function (resolve, reject) {
    
    ctx.lineWidth = strokeData.width;
    ctx.strokeStyle = strokeData.color;
    let posArr = strokeData.posArr;
    let count=0;
    for (let index = 1; index < posArr.length; index++) {
      setTimeout(() => {
        ctx.lineWidth = strokeData.width;
        ctx.strokeStyle = strokeData.color;       
        ctx.moveTo(posArr[index - 1].x * scale, posArr[index - 1].y * scale)
        ctx.lineTo(posArr[index].x * scale, posArr[index].y * scale)
        ctx.stroke()
        count++;
        if (count === posArr.length - 1) {
          ctx.beginPath(); 
          resolve();
        }
      }, posArr[index].delay)
    }
  });
}

function reDraw(ctx, drawData, scale) {
  console.log(drawData)
  let drawWork=reStroke(ctx, drawData[0], scale); 
  for (let index = 0; index < drawData.length-1; index++) {
    drawWork=drawWork.then(reStroke(ctx, drawData[index+1], scale))    
  }
}

function beginDraw(ctx, { lineWidth, color, x, y }, scale) {
  scale = scale || 1
  ctx.lineWidth = lineWidth
  ctx.strokeStyle = color
  ctx.beginPath()
  ctx.moveTo(x * scale, y * scale)
}

function drawAPoint(ctx, { x, y }, scale) {
  scale = scale || 1
  ctx.lineTo(x * scale, y * scale)
  ctx.stroke()
}

export default {
  drawByStrokeData,
  beginDraw,
  drawAPoint,
  reDraw
}
